package com.xopencode.netty.heima;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * @author Mcb
 * @date 2022/5/22
 * @apiNote 控制台输入字符进行发送，q为退出，并在线程关闭后进行指定操作
 */
@Slf4j
public class ChannelFutureClose {
    public static void main(String[] args) throws InterruptedException {
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                }).connect(new InetSocketAddress("localhost", 9090));

        Channel channel = channelFuture.sync().channel();
        log.debug("{}",channel);
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String str = scanner.nextLine();
                if (str.equalsIgnoreCase("q")){
                    channel.close(); //异步操作
                    log.debug("处理关闭之后的操作");
                    break;
                }
                channel.writeAndFlush(str);
            }
        },"WriteThread").start();



        ChannelFuture closeFuture = channel.closeFuture();

        //解决方式一：closeFuture异步关闭操作完了之后
        /*closeFuture.sync();
        log.debug("处理关闭之后的操作");*/

        //解决方式二：closeFuture添加channelFutureListener,异步操作完成，异步线程进行回调此函数
        closeFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("处理关闭之后的操作");
            }
        });
    }
}














